<template>
  <div v-show="$route.name == 'house-multi'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/house-list' }">仓库列表</el-breadcrumb-item>
      <el-breadcrumb-item>采购新品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-form :model="saveForm"
      :rules="saveFormRules"
      ref="saveFormRef"
      label-width="100px">
        <!-- 共同选项 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商" prop="gys">
              <el-input v-model="saveForm.gys"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
           <el-form-item label="日期" prop="date">
            <el-date-picker type="date" placeholder="选择日期" v-model="saveForm.date" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品表格 -->
        <el-row>
          <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
              <el-col :span="4">
                <el-button type="success" @click="showProductAddDialog()">新增</el-button>
              </el-col>
            </el-row>
            <!-- 商品列表区域 -->
            <el-table :data="saveForm.productList" border stripe height="300">
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="类型" prop="product"></el-table-column>
              <el-table-column label="名称" prop="productn"></el-table-column>
              <el-table-column label="规格" prop="model"></el-table-column>
              <el-table-column label="单位" prop="unit"></el-table-column>
              <el-table-column label="数量" prop="amoumt"></el-table-column>
              <el-table-column label="单价" prop="price"></el-table-column>
              <el-table-column label="进货金额" prop="total"></el-table-column>
              <el-table-column label="实付" prop="paid"></el-table-column>
              <el-table-column label="结算方式" prop="js"></el-table-column>
              <el-table-column label="备注" prop="other"></el-table-column>
              <el-table-column label="操作" width="120px">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showProductEditDialog(scope.row, scope.$index)"></el-button>
                  </el-tooltip>
                  <!-- 删除按钮 -->
                  <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteProduct(scope.row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col>
            <el-button @click="back">返回</el-button>
            <el-button type="primary" @click="save">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 保存商品对话框 -->
    <el-dialog :title="isProductAdd ? '新增商品' : '修改商品'" :visible.sync="saveProductDialogVisible" width="70%" @close="saveProductDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="saveProductForm" :rules="saveProductFormRules" ref="saveProductFormRef" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="product">
              <el-radio-group v-model="saveProductForm.product">
                <el-radio label="会议屏">会议屏</el-radio>
                <el-radio label="其他">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名称" prop="productn">
              <el-input v-model="saveProductForm.productn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格" prop="model">
              <el-input v-model="saveProductForm.model"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="saveProductForm.unit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="amoumt">
              <el-input-number v-model="saveProductForm.amoumt" controls-position="right" style="width: 100%" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价" prop="price">
              <el-input-number v-model="saveProductForm.price" controls-position="right" style="width: 100%" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="进货金额" prop="total">
              <el-input-number v-model="saveProductForm.total" controls-position="right" style="width: 100%" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实付" prop="paid">
              <el-input-number v-model="saveProductForm.paid" controls-position="right" style="width: 100%" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="other">
              <el-input v-model="saveProductForm.other"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="结算方式" prop="js">
              <el-radio-group v-model="saveProductForm.js">
                <el-radio label="赊销">赊销</el-radio>
                <el-radio label="现金">现金</el-radio>
                <el-radio label="银行存款">银行存款</el-radio>
                <el-radio label="预付">预付</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveProductDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      saveForm: {
        productList: [],
        amoumt: 1,
        price: 0,
        date: '',
        gys: '',
        total: 0
      },
      saveFormRules: {
        gys: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      // 是否新增商品
      isProductAdd: true,
      saveProductDialogVisible: false,
      // 添加新的商品
      saveProductForm: {
        product: '会议屏',
        productn: '',
        model: '',
        unit: '',
        amoumt: 1,
        price: '',
        total: '',
        paid: '',
        js: '现金',
        other: ''
      },
      // 添加表单的验证规则对象
      saveProductFormRules: {
        product: [{ required: true, message: '请选择类型', trigger: 'change' }],
        productn: [{ required: true, message: '请输入商品', trigger: 'blur' }],
        model: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        amoumt: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
        total: [{ required: true, message: '请输入进货金额', trigger: 'blur' }],
        paid: [{ required: true, message: '请输入实付', trigger: 'blur' }],
        js: [{ required: true, message: '请选择结算方式', trigger: 'change' }]
      },
      modifyProductIndex: 0
    }
  },
  watch: {
    'saveProductForm.amoumt': {
      handler: function(val, oldval) {
        this.saveProductForm.total = val * this.saveProductForm.price
      }
    },
    'saveProductForm.price': {
      handler: function(val, oldval) {
        this.saveProductForm.total = val * this.saveProductForm.amoumt
      }
    },
    'saveProductForm.total': {
      handler: function(val, oldval) {
        this.saveProductForm.price = val / this.saveProductForm.amoumt
      }
    }
  },
  mounted() {
    const myDate = new Date()
    const year = myDate.getFullYear() // 获取当前年份
    const month = myDate.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
    const day = myDate.getDate() // 获取当前日（1-31）
    // 日期格式：2019/07/29 - 2019/07/29
    this.saveForm.date = `${year}-${month}-${day}`
  },
  methods: {
    // 显示商品对话框
    showProductAddDialog() {
      this.isProductAdd = true
      this.saveProductForm = {
        product: '会议屏',
        productn: '',
        model: '',
        unit: '',
        amoumt: 1,
        price: '',
        total: '',
        paid: '',
        js: '现金',
        other: ''
      }
      this.saveProductDialogVisible = true
    },
    // 点击按钮，保存入库单
    async save() {
      this.$refs.saveFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发起新增入库单的网络请求
        const { data: result } = await this.$http.post('/goods-multi', {
          goods: this.saveForm
        })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        if (result.data !== 'ok') {
          const h = this.$createElement
          this.$confirm('提示', {
            title: '提示',
            message: h('div',[h('p', '请确认以下商品是否添加为下列库存商品，若不是请重新修改名称：'), h('p', result.data)]),
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const { data: result1 } = await this.$http.post('/goods-multi', { goods: this.saveForm, isAdd: 1 })
            if (result1.status !== 200) {
              return this.$message.error(result1.msg)
            }
            this.$message.success('保存入库单成功！')
            this.$router.push({ path: '/purchase-list' })
          })
          return
        }
        this.$message.success('保存入库单成功！')
        this.$router.push({ path: '/purchase-list' })
      })
    },
    // 监听新增商品对话框的关闭事件
    saveProductDialogClosed() {
      if (this.isProductAdd) {
        this.$refs.saveProductFormRef.resetFields()
      }
    },
    // 点击按钮，添加商品
    saveProduct() {
      this.$refs.saveProductFormRef.validate(async (valid) => {
        if (!valid) return
        var product = this.$_.cloneDeep(this.saveProductForm)
        // 修改
        if (!this.isProductAdd) {
          this.saveForm.productList.splice(this.modifyProductIndex, 1, product)

          this.$message.success('修改商品成功！')
        } else {
          // 新增
          this.saveForm.productList.push(product)
          this.$message.success('添加商品成功！')
        }
        // 隐藏添加商品的对话框
        this.saveProductDialogVisible = false
      })
    },
    // 显示修改商品对话框
    showProductEditDialog(contact, index) {
      this.isProductAdd = false
      this.saveProductForm = this.$_.cloneDeep(contact)
      this.modifyProductIndex = index
      this.saveProductDialogVisible = true
    },
    // 删除商品
    async deleteProduct(product) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该商品，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      this.saveForm.productList.splice(
        this.saveForm.productList.findIndex((existedProduct) => existedProduct === product),
        1
      )
      this.$message.success('删除商品成功！')
    },
    // 返回
    back() {
      this.$router.push({ 'name': 'house-list' })
    }
  }
}
</script>

<style lang="less" scoped>
.query {
  margin-bottom: 20px;
}
.el-select {
  width: 100%;
}
.el-date-editor {
  width: 100%;
}
.el-message-box {
  width: 573px;
}
</style>
